package com.blac.bridge

import android.app.Activity
import android.os.Handler
import android.os.Looper
import com.blac.Business
import java.lang.ref.WeakReference
import java.lang.reflect.Method

object CocosBridge {
    var mainGameActivity:WeakReference<Activity>?=null
    private var evalString: Method?=null
    private var runOnGLThread:Method?=null
    private val handler:Handler = Handler(Looper.getMainLooper())

    fun setMainGameActivity(activity: Activity){
        mainGameActivity = WeakReference(activity)
    }

    fun XSSdkCallback(action:String,jsonData:String){
       mainGameActivity?.get()?:return
        handler.post {
            if (runOnGLThread ==null){
                try {
                    val clzCocos2dAct =Class.forName(Business.COCOS2DX_ACTIVITY_PATH,false,
                        Business.mContext.get()?.classLoader)
                    runOnGLThread = clzCocos2dAct.getDeclaredMethod("runOnGLThread",Runnable::class.java)
                    runOnGLThread?.isAccessible = true
                }catch (e:Exception){
                    e.printStackTrace()
                }

                try {
                    check()
                    callback(action,jsonData)
                }catch (e:Exception){
                    e.printStackTrace()
                }

            }
        }
    }

    private fun callback(action: String, jsonData: String) {
        val activity= mainGameActivity?.get()?:return
        runOnGLThread?.invoke(activity, Runnable {
            try {
                evalString?.invoke(null,"window.AdCallback('$action','$jsonData')")
            }catch (e:Exception){
                e.printStackTrace()
            }
        })
    }


    private fun check() {
        if (evalString == null){
            try {
                val clzBridge=Class.forName(Business.COCOS2DX_JJB_PATH,false,Business.mContext?.get()?.classLoader)
                evalString=clzBridge.getDeclaredMethod("evalString",String::class.java)
                evalString?.isAccessible = true
            }catch (e:Exception){
                e.printStackTrace()
            }
        }

    }

}